package com.steven.concurrent.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 
 * Description:尝试获取锁 
 * 
 * @author hzg
 * @Date   下午4:11:25
 *
 */
public class AttemptLocking {
	private ReentrantLock lock = new ReentrantLock();
	public void untimed() {
		boolean captured = lock.tryLock();
		try {
			System.out.println("tryLock(): "+captured);
		} finally {
			if (captured) {
				lock.unlock();
			}
		}
	}
	
	public void timed() {
		boolean captured = false;
		try {
			captured = lock.tryLock(2, TimeUnit.SECONDS);
		} catch(InterruptedException ex) {
			throw new RuntimeException(ex);
		}
		try {
			System.out.println("tryLock(2, TimeUnit.SECONDS): " + captured);
		} finally {
			if (captured) {
				lock.unlock();
			}
		}
	}
	
	public static void main(String[] args) {
		final AttemptLocking al = new AttemptLocking();
		al.untimed();
		al.timed();
		// 创建一个新的线程获取锁
		Thread t = new Thread() {
			{
				setDaemon(true);
			}
			@Override
			public void run() {
				al.lock.lock();
				System.out.println("acquired");
			}
		};
		t.start();
		
		try {
			t.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		al.untimed();
		al.timed();
	}
}
